package com.example.demo.controller;

import com.example.demo.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FileController {
   private static List<String> fileNames = new ArrayList<>();

    private String uploadPath="D:\\file\\";
    Logger logger = LoggerFactory.getLogger(FileController.class);
    @GetMapping("/uploadfile")
    public String uploadfile(){
        return "uploadfile";
    }
    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file) {
        Map<String,Object> map=new HashMap();
        map.put("status",0);
        try {
            String fileName = FileUtil.uploadFile(file, uploadPath);
            map.put("filename",fileName);
        } catch (Exception e) {
            map.put("status",-1);
            map.put("message",e.getMessage());
        }
        return map;
    }
    @PostMapping("/uploads")
    @ResponseBody
    public Object uploads(@RequestParam("files") MultipartFile[] files) {
        Map<String,Object> map=new HashMap();
        map.put("status",0);

            for (MultipartFile file: files) {
                try {
                    String fn = FileUtil.uploadFile(file, uploadPath);
                    fileNames.add(fn);
                } catch (Exception e) {
                    map.put("status",-1);
                    map.put("message",e.getMessage());
                    return  map;
                }
            }
        map.put("filename",fileNames);
        return map;
    }
    @GetMapping("/downloadfile")
    public String downloadfile(Model model){
        List<String> filenames = FileUtil.getFileNamesFromDir(uploadPath);
        model.addAttribute("filenames",filenames);
        return "downloadfile";
    }
    @ResponseBody
    @GetMapping("/download/{filename}")
    public void download(@PathVariable("filename") String fileName, HttpServletResponse response) {
        try {
            FileUtil.downloadFile(uploadPath,fileName,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
